package com.itc.dispatch.common;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itc.common.core.domain.R;
import com.itc.dispatch.domain.AlarmCentre;
import com.itc.dispatch.domain.AlarmConfig;
import com.itc.dispatch.domain.AlarmRule;
import com.itc.dispatch.domain.FlightOperationMonitoring;
import com.itc.dispatch.domain.customDomain.CusAlarmCentre;
import com.itc.dispatch.service.AlarmCentreService;
import com.itc.dispatch.service.AlarmConfigService;
import com.itc.dispatch.service.AlarmRuleService;
import com.itc.dispatch.service.FlightOperationMonitoringService;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.*;
import java.time.temporal.Temporal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务存放
 */
@Component
public class MethodTask {

    @Autowired
    public AlarmRuleService alarmRuleService;

    @Autowired
    public AlarmCentreService alarmCentreService;


    @Autowired
    public AlarmConfigService alarmConfigService;

    @Autowired
    public FlightOperationMonitoringService flightService;

    //存储实时数据
    public static List<Object> oldList ;

    //是否添加标志
    public static Boolean saveConfirm=false;

    public static Boolean  continueIf=true;

    //指标类型满足规则数量
    public static Integer isSolvenum=0;

    //表名
    public static   String tableName="";
    //字段名
    public static   String fieldName="";

    //记录当前rule号
    public static  Long  isRepNumber=0l;


    //创建定时任务线程池
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private ScheduledFuture<?> scheduledFuture;
    private static boolean taskBegin = true;
    public static Long id;
    public  void autoMethodTask(Long seconds,Long ruleId){
            long delayInMillis = seconds * 1000;
            if (scheduledFuture != null && !scheduledFuture.isDone()) {
                scheduledFuture.cancel(false);  // 取消当前任务
            }
            taskBegin=true;
            id=ruleId;
            //延迟delayInMillis豪秒后执行
            scheduledFuture = scheduler.scheduleAtFixedRate(this::scheduledTask, delayInMillis, delayInMillis, TimeUnit.MILLISECONDS);
    }
    //执行任务
    public void scheduledTask() {
        if (taskBegin){
            //查出对应的告警中心
            LambdaQueryWrapper<AlarmCentre> centreLambdaQueryWrapper = new LambdaQueryWrapper<>();
            centreLambdaQueryWrapper.eq(AlarmCentre::getRuId,id);
            centreLambdaQueryWrapper.last("limit 1");
            AlarmCentre one = alarmCentreService.getOne(centreLambdaQueryWrapper);
            if (one == null){
                throw new NullPointerException("查询对应数据有误");
            }
            one.setAlarmStatus(0);
            alarmCentreService.updateById(one);
            taskBegin=false;
        }
        scheduledFuture.cancel(false);
    }






    //定时任务获取数据是否变化，测试每秒监听一次
    @Scheduled(cron = "*/1 * * * * *")
    @Transactional
    public void autoGetDatas(List<AlarmRule> alarmRules){
        ArrayList<AlarmCentre> alarmCentreList = new ArrayList<>();
        for (AlarmRule alarmRule : alarmRules) {

            //已触发当前规则直接结束方法
            if (alarmRule.getIsSolve().intValue() == Constents.Int_1){
                return;
            }
            AlarmConfig configone = alarmConfigService.getById(alarmRule.getAcId());
            if (configone == null){
                throw new NullPointerException("查询告警中心有误");
            }
            QueryWrapper<FlightOperationMonitoring> queryWrapper = new QueryWrapper<>();
//            queryWrapper.select(SnakeTool.convertCamelToSnake(alarmRule.getFieldName()));
            List<Object> list = flightService.listObjs(queryWrapper);
            //数值类型
            if (alarmRule.getAlarmType().intValue() == Constents.Int_1){
                int beginNumber;
                int endNumber;
                int numberValue = 0;
                for (Object data : list) {
                   //包含/不包含
                    if (alarmRule.getCondition().intValue() == Constents.Int_6 || alarmRule.getCondition().intValue() == Constents.Int_7 ){
                        String[] split = alarmRule.getConditionValue().split(",");
                        beginNumber=Integer.parseInt(split[0]);
                        endNumber=Integer.parseInt(split[1]);
                        Integer indexLeftTail = alarmRule.getIndexLeftTail();
                        Integer indexRightTail = alarmRule.getIndexRightTail();
                        //包含
                        if (alarmRule.getCondition().intValue() == Constents.Int_6){
                            // 根据条件类型判断并触发告警
                            if (indexLeftTail == 0 && indexRightTail == 0 ) {
                                if ((int) data > beginNumber && (int) data < endNumber) {
                                    saveConfirm = true;
                                }
                            } else if (indexLeftTail == 1 && indexRightTail == 0) {
                                if ((int) data >= beginNumber && (int) data < endNumber) {
                                    saveConfirm = true;
                                }
                            } else if (indexLeftTail == 0 && indexRightTail == 1) {
                                if ((int) data > beginNumber && (int) data <= endNumber) {
                                    saveConfirm = true;
                                }
                            } else if (indexLeftTail == 1 && indexRightTail == 1) {
                                if ((int) data >= beginNumber && (int) data <= endNumber) {
                                    saveConfirm = true;
                                }
                            } else {
                                throw new NullPointerException("告警条件参数传递错误");
                            }
                            break;
                        }
                        //不包含
                        if (indexLeftTail == 0 && indexRightTail == 0 ) {
                            if ((int) data < beginNumber && (int) data > endNumber) {
                                saveConfirm = true;
                            }
                        } else if (indexLeftTail == 1 && indexRightTail == 0) {
                            if ((int) data <= beginNumber && (int) data > endNumber) {
                                saveConfirm = true;
                            }
                        } else if (indexLeftTail == 0 && indexRightTail == 1) {
                            if ((int) data < beginNumber && (int) data >= endNumber) {
                                saveConfirm = true;
                            }
                        } else if (indexLeftTail == 1 && indexRightTail == 1) {
                            if ((int) data <= beginNumber && (int) data >= endNumber) {
                                saveConfirm = true;
                            }
                        } else {
                            throw new NullPointerException("告警条件参数传递错误");
                        }
                        break;
                    }
                    //其他条件
                    numberValue =Integer.parseInt(alarmRule.getConditionValue());
                    // 根据条件类型判断并触发告警
                    switch (alarmRule.getCondition()) {
                        case 0: // 条件为等于
                            if ((int)data == numberValue) {
                                saveConfirm = true;
                            }
                            break;
                        case 1: // 条件为小于
                            if ((int) data < numberValue) {
                                saveConfirm = true;
                            }
                            break;
                        case 2: // 条件为大于
                            if ((int) data > numberValue) {
                                saveConfirm = true;
                            }
                            break;
                        case 3: // 条件为大于等于
                            if ((int) data >= numberValue) {
                                saveConfirm = true;
                            }
                            break;
                        case 4: // 条件为小于等于
                            if ((int) data <= numberValue) {
                                saveConfirm = true;
                            }
                            break;
                        case 5: // 条件为不等于
                            if ((int) data != numberValue) {
                                saveConfirm = true;
                            }
                            break;
                        default:
                            throw new NullPointerException("告警条件参数传递错误");
                    }
                }
//
            }
            //时间跳变类型新增告警
            if (alarmRule.getAlarmType().intValue() == Constents.Int_2){
               //转为数字
                long timeValue= Long.parseLong(alarmRule.getConditionValue());
                if (oldList == null || oldList.equals(list)) {
                    //初始化/更新
                    oldList=list;
                    return;
                }
                //数据发生变化情况
                for (Object newTime : list) {
                    for (Object oldTime : oldList) {
                        Duration duration = Duration.between((LocalDateTime) oldTime, (LocalDateTime) newTime);
                        long seconds = duration.getSeconds();
                        switch (alarmRule.getCondition()){
                            case 8:
                                //往前跳变。包含
                                if(seconds <= timeValue){
                                    saveConfirm = true;
                                }
                                break;
                            case 9:
                                //往前跳变。不包含
                                if(seconds > timeValue){
                                    saveConfirm = true;
                                }
                                break;
                            case 10:
                                //往后跳变。包含
                                if(-seconds <= timeValue){
                                    saveConfirm = true;
                                }
                                break;
                            case 11:
                                //往后跳变。不包含
                                if(-seconds > timeValue){
                                    saveConfirm = true;
                                }
                                break;
                            default:
                                throw new NullPointerException("传值不正确");
                        }
                    }

                }
            }
            //文本类型新增告警

            if (alarmRule.getAlarmType().intValue() == Constents.Int_3 ){
                for (Object text : list) {
                    String stringText= (String) text;
                    //跳变类型
                    if (alarmRule.getCondition() == 12){
                        if (oldList == null || oldList.equals(list)){
                            //初始化/更新
                            oldList=list;
                            return;
                        }
                        saveConfirm = true;
                        return;
                    }
                   //非跳变类型
                    String textValue = alarmRule.getConditionValue();
                    switch (alarmRule.getCondition()) {
                        case 0: // 条件为等于
                            if ( text.equals(textValue) ) {
                                saveConfirm = true;
                            }
                            break;
                        case 5: // 条件不等于
                            if (!text.equals(textValue)) {
                                saveConfirm = true;
                            }
                            break;
                        case 6: // 条件包含
                            if (stringText.contains(textValue)) {
                                saveConfirm = true;
                            }
                            break;
                        case 7: // 条件为不包含
                            if (!stringText.contains(textValue)) {
                                saveConfirm = true;
                            }
                            break;
                        default:
                            throw new NullPointerException("告警条件参数传递错误");
                    }
                }
            }
            //时间跳变/文本类型满足条件直接新增告警中心
            if (saveConfirm){
//                AlarmCentre alarmCentre = new AlarmCentre();
//                alarmCentre.setAlarmStatus(1);
//                alarmCentre.setAlarmGrade(alarmRule.getAlarmGrade());
//                alarmCentre.setAlarmName(configone.getAlarmName());
//                alarmCentre.setAlarmType(configone.getAlarmType());
//                alarmCentre.setAlarmTime(LocalDateTime.now());
//                alarmCentre.setAlarmMsg(alarmRule.getDescribe());
//                alarmCentre.setRuId(alarmRule.getId());
//                alarmCentre.setTablesName(alarmRule.getTablesName());
//                alarmCentre.setFieldName(alarmRule.getFieldName());
//                ZonedDateTime zonedDateTime = alarmRule.getCreateDate().atZone(ZoneId.systemDefault());
//                Date from = Date.from(Instant.from(zonedDateTime));
//                alarmCentre.setRuCreateDate(from);
//                alarmCentreService.save(alarmCentre);
//                //该规则成功修改
//                alarmRule.setIsSolve(1);
//                alarmRuleService.updateById(alarmRule);
//                saveConfirm=false;
//                //自动计时开始
//                long time= 0L;
//                switch (configone.getAlarmTimeUnit()){
//                    case 0:
//                        //毫秒
//                        time = (long) (configone.getAlarmTimeValue() / 1000);
//                        break;
//                    case 1:
//                        //秒
//                        time = (long) (configone.getAlarmTimeValue());
//                        break;
//                    case 2:
//                        //分
//                        time = (long) (configone.getAlarmTimeValue() * 60);
//                        break;
//                    case 3:
//                        //时
//                        time = (long) (configone.getAlarmTimeValue() * 60 * 60);
//                        break;
//                    default:
//                        throw new NullPointerException("单位错误");
//                }
//                    autoMethodTask(time,alarmRule.getId());
//                //结束本次循环
//                break;

            }
        }
//        //多条指标类型，只用添加同表同字段最高等级的告警数据
//        if (isSolvenum > 1){
//            //取出
//            LambdaQueryWrapper<AlarmRule> ruleLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            ruleLambdaQueryWrapper.eq(AlarmRule::getIsRepeat,isRepNumber);
//            ruleLambdaQueryWrapper.eq(AlarmRule::getCreateDate,now);
//            ruleLambdaQueryWrapper.
//            List<AlarmRule> list = alarmRuleService.list(ruleLambdaQueryWrapper);
//        }
//      //只有一条指标类型数据情况直接保存
//        alarmCentreService.saveBatch(alarmCentreList);
    }





}
